<script setup lang="ts">

import {ref} from "vue";
import {ElNotification, FormInstance, FormRules, UploadProps, UploadRawFile} from "element-plus";
import axios from "axios";
import {ServerHost} from "@/main.js";
import {v4 as uuidv4} from "uuid";
import {Plus} from "@element-plus/icons-vue";
import {downloadImg} from "@/utils";

// post or edit
const props = defineProps(['type', 'policy'])

const policy = ref({
  id: "",
  title: "",
  content: "",
  postTime: new Date(),
  author: "",
  pageView: 0,
  coverImg: "",
});
const coverImgUrl = ref("")

const isLoadingList = ref(false)
if (props.type === 'edit') {
  policy.value = props.policy
  policy.value.postTime = new Date(props.policy.postTime)
  // 下载封面
  if (props.policy.coverImg) {
    isLoadingList.value = true
    downloadImg(props.policy.coverImg, "PolicyCover/")
        .then(res => {
          if (res.status === 200) {
            const type = props.policy.coverImg.split('.')[1]
            let mime: string
            if ((['jpg', 'jpeg'] as any).includes('jpg'))
              mime = 'image/jpeg'
            else
              mime = `image/${type}`
            const blob = new Blob([res.data], {type: mime})
            coverImgFile = new File([blob], props.policy.coverImg, {type: mime})
            coverImgUrl.value = URL.createObjectURL(coverImgFile)
            isLoadingList.value = false
          }
        })
  }

}

if (props.type === 'new') {
  // 每隔1s更新一次发布时间
  setInterval(() => {
    policy.value.postTime = new Date()
  }, 1000)
}

const policyFormRef = ref<FormInstance>()

const validateTitle = (rule: any, value: any, callback: any) => {
  console.log(value)
  if (!value) {
    callback(new Error('请输入标题'))
  } else {
    callback()
  }
}

const validateContent = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入内容'))
  } else {
    callback()
  }
}

const policyRules = ref<FormRules<typeof policy>>({
  title: [{validator: validateTitle, trigger: 'blur'}],
  content: [{validator: validateContent, trigger: 'blur'}],
})

let coverImgFile: File

const verifyImg = (rawFile: UploadRawFile) => {
  return !(rawFile.size > 1024 * 1024)
}

const isChangeCoverImg = ref(false)
const onAddImg: UploadProps['beforeUpload'] = (rawFile: UploadRawFile) => {

  if (!verifyImg(rawFile)) {
    return
  }

  console.log(rawFile)
  coverImgFile = rawFile
  coverImgUrl.value = URL.createObjectURL(rawFile)

  if (props.type === 'edit') {
    isChangeCoverImg.value = true
  }

}

const onPostNewPolicy = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {

      //有封面则传封面
      policy.value.coverImg = UploadCoverImg() as string

      // 生成uuid
      policy.value.id = uuidv4()
      policy.value.pageView = 0

      console.log('start submit!')
      console.log(policy.value)
      axios.post(`${ServerHost}/postNewPolicy`, policy.value)
          .then((res) => {
            if (res.status === 200) {
              // 清空内容
              policy.value.title = ""
              policy.value.content = ""
              // 清空封面
              policy.value.postTime = ""
              coverImgUrl.value = ""
              coverImgFile = undefined
              ElNotification({
                title: '政策发布成功',
                type: 'success',
                position: 'bottom-right',
              })
            } else {
              ElNotification({
                title: '政策发布失败',
                type: 'error',
                position: 'bottom-right',
              })
            }
          })
    } else {
      console.log('error submit!')
    }
  })
}

const emit = defineEmits(["getValue"])

const onUpdatePolicy = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {

      //有封面改动则传封面
      if (isChangeCoverImg.value) {
        policy.value.coverImg = UploadCoverImg()
      }

      console.log(policy.value)
      console.log('start submit!')
      axios.post(`${ServerHost}/updatePolicy`, policy.value)
          .then((res) => {
            if (res.status === 200) {
              emit("getValue", true)
              ElNotification({
                title: '政策修改成功',
                type: 'success',
                position: 'bottom-right',
              })
            } else {
              ElNotification({
                title: '政策修改失败',
                type: 'error',
                position: 'bottom-right',
              })
            }
          })


    } else {
      console.log('error submit!')
    }

  })
}

// 覆盖自带的上传行为
const onImgUpload = () => {
  console.log('onImgUpload')
}

const UploadCoverImg = (): String => {
  let fileName = ""
  console.log(coverImgFile)
  if (!(typeof coverImgFile === "undefined")) {
    fileName += uuidv4()
    const fileFormat = coverImgFile.type.split("/")[1]
    fileName += '.' + fileFormat

    axios.post(`${ServerHost}/postFile`, {file: coverImgFile}, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
      params: {
        "name": fileName,
        "path": "PolicyCover/"
      }
    })
        .then(res => {
          if (res.status === 200) {
            ElNotification({
              title: '图片上传成功',
              type: 'success',
              position: 'bottom-right',
            })
          } else {
            ElNotification({
              title: '图片上传失败',
              type: 'error',
              position: 'bottom-right',
            })
          }
        })
    return fileName
  } else {
    return ""
  }
}

const onDeletePolicy = () => {
  console.log(policy.value.id)
  axios.post(`${ServerHost}/deletePolicy?id=${policy.value.id}`,)
      .then(res => {
        if (res.status === 200) {
          emit("getValue", true)
          ElNotification({
            title: '政策删除成功',
            type: 'success',
            position: 'bottom-right',
          })
        } else {
          ElNotification({
            title: '政策删除失败',
            type: 'success',
            position: 'bottom-right',
          })
        }
      })
}
</script>

<template>
  <el-form ref="policyFormRef" :rules="policyRules" :model="policy">
    <el-form-item label="政策封面" prop="title">
      <div class="cover-img-upload">
        <el-upload
            class=""
            drag
            :http-request="onImgUpload"
            :before-upload="onAddImg"
            :show-file-list="false"
            v-loading="isLoadingList"
        >
          <el-image v-if="coverImgUrl" fit="contain" :src="coverImgUrl" class="cover-img"
                    alt="Cover Img"/>
          <el-icon v-else class="cover-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </div>
    </el-form-item>
    <el-form-item label="政策标题" prop="title">
      <el-input v-model="policy.title" placeholder="请输入政策标题"></el-input>
    </el-form-item>
    <el-form-item label="政策内容" prop="content">
      <el-input v-model="policy.content" type="textarea" :rows="10" placeholder="请输入政策内容"></el-input>
    </el-form-item>
    <el-form-item label="发布时间">
      <el-date-picker
          v-model="policy.postTime"
          type="datetime"
          :readonly="true"
      />
    </el-form-item>
    <el-form-item>
      <el-button v-if="props.type === 'new'" type="primary" @click="onPostNewPolicy(policyFormRef)">发布</el-button>
      <el-button v-if="props.type === 'edit'" type="primary" @click="onUpdatePolicy(policyFormRef)">确认修改</el-button>
      <el-popconfirm
          v-if="props.type === 'edit'"
          width="auto"
          title="确定要删除吗"
          confirm-button-text="确认删除"
          confirm-button-type="danger"
          cancel-button-text="取消"
          placement="top"
          @confirm="onDeletePolicy"
      >
        <template #reference>
          <el-button type="danger">删除</el-button>
        </template>
      </el-popconfirm>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">

$cover-img-size: 200px;

.cover-img-upload {
  width: $cover-img-size;
  height: $cover-img-size;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
}

.cover-img-upload:hover {
  border-color: var(--el-color-primary);
}

.cover-img, .cover-uploader-icon {
  width: $cover-img-size;
  height: $cover-img-size;
}

</style>
